package com.ruoyi.common.excel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.ruoyi.common.utils.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

public class GlobalDateConverter implements Converter<Date> {

    @Override
    public Class<Date> supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    // ✅ 只重写这一个方法即可
    @Override
    public Date convertToJavaData(ReadConverterContext<?> context) {
        ReadCellData<?> cellData = context.getReadCellData();
        // 下面逻辑同之前
        if (cellData.getType() == CellDataTypeEnum.EMPTY) return null;
        if (cellData.getType() == CellDataTypeEnum.NUMBER) {
            return DateUtil.getJavaDate(cellData.getNumberValue().doubleValue());
        }
        String str = cellData.getStringValue();
        if (StringUtils.isBlank(str)) return null;
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str.trim());
        } catch (Exception e1) {
            try {
                return new SimpleDateFormat("yyyy-MM-dd").parse(str.trim());
            } catch (Exception e2) {
                return null;
            }
        }
    }
}
